<script setup>
console.log("index.vue")
const nameTask = ref('')

const { pending, data: tasks, refresh: getTasks } = await useFetch("http://localhost:8000/tasks", {
})

async function deleteTask(task_id) {
	const response = await $fetch(`http://localhost:8000/tasks/${task_id}`, {
		method: "DELETE",
	})
	getTasks()
}

async function completeTask(task) {
	const response = await $fetch(`http://localhost:8000/tasks/${task.id}`, {
		method: "PATCH",
		body: {
			name: task.name,
			completed: true,
		}
	})
	getTasks()
}

async function addTask() {
	const response = await $fetch("http://localhost:8000/tasks", {
		method: 'POST',
		body: {
			name: nameTask.value,
			completed: false,
		},
	})
	console.log("addTask", response)
	getTasks();
}

</script>

<template>
	<div>
		{{ pending ? "Загрузка" : "" }}
		<div class="max-w-sm px-2 flex flex-row gap-2">
			<div>
				<UInput class="p-2" v-model="nameTask" placeholder="Введите название задачи" />
			</div>
			<div>
				<UButton class="p-2" @click="addTask" label="Добавить задаачу" />
			</div>
		</div>
		<div v-auto-animate>
			<div v-for="task in tasks" :key="task.id" class="text-bold text-center p-2">
				<div :class="[task.completed ? 'flex flex-row bg-green-400 gap-4' : 'flex flex-row gap-4']">
					<div v-if="!task.completed">
						<UButton label="Выполнено" @click="completeTask(task)" />
					</div>
					<div>{{ task.name }}</div>
					<div>
						<UButton label="Удалить" color="red" @click="deleteTask(task.id)" />
					</div>
				</div>
			</div>
		</div>
	</div>
</template>
